<template>
	<view class="wrap">
		<view class="main">
			<g-item>
				<template v-slot:left>客户名称</template>
				<template v-slot:right>
					<input v-model="customInfo.name" type="text" placeholder="请输入客户名称" placeholder-class="app_phc" />
				</template>
			</g-item>
			<g-item>
				<template v-slot:left>联系电话</template>
				<template v-slot:right>
					<input v-model="customInfo.tel" type="text" placeholder="请输入联系电话" placeholder-class="app_phc" />
				</template>
			</g-item>
			<g-item>
				<template v-slot:left>客户类型</template>
				<template v-slot:right>
					<view class="picker app_arrow" :style="{color: customTypeText == '请选择'? '': '#333'}"
						@click="openCustomerTypePop">{{customTypeText}}</view>
				</template>
			</g-item>
			<g-item>
				<template v-slot:left>所在地区</template>
				<template v-slot:right>
					<!-- <picker mode="multiSelector" :range="areaList" range-key="label" @columnchange="onColumnChange">
						<view class="picker app_arrow">请选择</view>
					</picker> -->
					<view class="picker app_arrow" @click="showRegionFlag = true">
						{{selectArea.length == 3 ? `${selectArea[0].label}${selectArea[1].label}${selectArea[2].label}` : '请选择'}}
					</view>
				</template>
			</g-item>
			<g-item>
				<template v-slot:left>详细地址</template>
				<template v-slot:right>
					<input v-model="customInfo.address" type="text" placeholder="请输入街道、楼号等"
						placeholder-class="app_phc" />
				</template>
			</g-item>
		</view>
		<view class="btn">
			<g-btn title="保存" :customstyle="{opacity: canSubmit?'1':'0.5'}" @click="onConfirmTap"></g-btn>
		</view>

		<!-- <u-picker mode="region" v-model="showRegionFlag" title="选择地区"></u-picker> -->
		<u-select mode="mutil-column-auto" v-model="showRegionFlag" :list="areaList" @confirm="confirm"
			:default-value="regionDefault"></u-select>

		<u-popup v-model="showCustomerTypePop" mode="bottom" border-radius="10">
			<view class="customerTypePop">
				<image class="customerTypePop-close" src="../../static/images/icon-close.png"></image>
				<view class="customerTypePop-header">
					<text>选择客户类型</text>
				</view>
				<view class="customerTypePop-main">
					<view class="customerTypePop-main_item" :class="{active: item.active}"
						v-for="(item, index) in customTypeList" :key="index" @click="onCustomerTypeTap(index)">
						{{item.customerType}}
					</view>
				</view>
				<view class="customerTypePop-btn">
					<g-btn title="确定" @click="onCustomerTypePopConfirm"></g-btn>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pageType: 'add',
				showRegionFlag: false,
				showCustomerTypePop: false,
				customInfo: {
					address: '',
					city: '',
					county: '',
					id: '',
					name: '',
					province: '',
					tel: '',
					type: '',
				},
				customTypeText: '请选择',
				customTypeList: [],
				tempAreaList: [],
				areaList: [],
				selectArea: [],
				regionDefault: [0, 0, 0]
				// provinceList: [], // 省
				// cityList: [], // 市
				// districtList: [] // 区
			}
		},
		computed: {
			canSubmit() {
				const ci = this.customInfo
				return true
				// return ci.address &&
				// 	ci.city &&
				// 	ci.county &&
				// 	ci.name &&
				// 	ci.province &&
				// 	ci.tel &&
				// 	ci.type
			}
		},
		onLoad(options) {
			this.pageType = options.pageType || 'add'
			if (this.pageType == 'edit' && options.userInfo) {
				const userInfo = JSON.parse(options.userInfo)
				this.customInfo = {
					address: userInfo.address,
					city: userInfo.city,
					county: userInfo.county,
					id: userInfo.id,
					name: userInfo.name,
					province: userInfo.province,
					tel: userInfo.tel,
					type: userInfo.type,
				}
				if (!userInfo.id) {
					this.pageType = 'add'
				} else {
					uni.setNavigationBarTitle({
						title: '编辑信息'
					})
				}
			}
			this.updatePage()
			this.$store.dispatch('updateUserInfo')
		},
		methods: {
			updatePage() {
				this.getAreaList()
				this.getCustomTypeList()
			},
			openCustomerTypePop() {
				this.customTypeList.forEach((item, index) => {
					item.active = item.id == this.customInfo.type
				})
				this.showCustomerTypePop = true
			},
			onCustomerTypeTap(idx) {
				this.customTypeList.forEach((item, index) => {
					item.active = index == idx
				})
			},
			getCustomTypeList() {
				this.$g_api.saleslipCustomerTypeList({
					userId: 1
				}).then(({
					data
				}) => {
					if (data?.length > 0) {
						data.forEach(item => {
							if (item.id == this.customInfo.type) {
								item.active = true
								this.customTypeText = item.customerType
							} else {
								item.active = false
							}

						})
						this.customTypeList = data
					}
				})
			},
			onCustomerTypePopConfirm() {
				let typeItem = this.customTypeList.find(item => item.active)
				console.log(typeItem);
				if (typeItem) {
					this.customInfo.type = typeItem.id
					this.customTypeText = typeItem.customerType
					this.showCustomerTypePop = false
				}
			},
			async getAreaList() {
				try {
					let provinceList = await this.getProvinceList()
					provinceList = provinceList.map(item => {
						item.children = item.children.map(val => {
							val.children = val.children.map(value => {
								return {
									value: value.id,
									label: value.name
								}
							})
							return {
								children: val.children,
								value: val.id,
								label: val.name
							}
						})
						return {
							children: item.children,
							value: item.id,
							label: item.name
						}
					})

					this.areaList = provinceList
					let countyIndex = 0
					let cityIndex = 0
					let provinceIndex = 0
					if (this.customInfo.province) {
						provinceIndex = provinceList.findIndex(item => item.value == this.customInfo.province)
						if (provinceIndex >= 0) {
							this.$set(this.regionDefault, 0, provinceIndex)
							this.$set(this.selectArea, 0, {
								label: provinceList[provinceIndex].label,
								value: provinceList[provinceIndex].value
							})
						}
					}
					if (this.customInfo.city) {
						cityIndex = provinceList[provinceIndex].children.findIndex(item => item.value == this
							.customInfo.city)
						if (cityIndex >= 0) {
							this.$set(this.regionDefault, 1, cityIndex)
							this.$set(this.selectArea, 1, {
								label: provinceList[provinceIndex].children[cityIndex].label,
								value: provinceList[provinceIndex].children[cityIndex].value
							})
						}
					}
					if (this.customInfo.county) {
						countyIndex = provinceList[provinceIndex].children[cityIndex].children.findIndex(item =>
							item.value == this.customInfo.county)
						if (countyIndex >= 0) {
							this.$set(this.regionDefault, 2, countyIndex)
							this.$set(this.selectArea, 2, {
								label: provinceList[provinceIndex].children[cityIndex].children[countyIndex]
									.label,
								value: provinceList[provinceIndex].children[cityIndex].children[countyIndex]
									.value
							})
						}
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			getProvinceList() {
				return new Promise((resolve, reject) => {
					this.$g_api.saleslipProvinceList().then(({
						data
					}) => {
						if (data?.length > 0) {
							resolve(data)
						} else {
							reject()
						}
					})
				})
			},
			getDistrictList(pid) {
				return new Promise((resolve, reject) => {
					this.$g_api.saleslipDistrictList({
						pid
					}).then(({
						data
					}) => {
						if (data?.length > 0) {
							resolve(data)
						} else {
							reject()
						}
					})
				})
			},
			onConfirmTap() {
				if (!this.canSubmit) return
				const customInfo = this.customInfo
				const selectArea = this.selectArea
				if (!customInfo.name) {
					uni.showToast({
						title: '请输入客户名称',
						icon: 'none'
					})
					return
				}
				if (!customInfo.tel) {
					uni.showToast({
						title: '请输入联系电话',
						icon: 'none'
					})
					return
				}
				const typeItem = this.customTypeList.find(item => item.active)
				if (!typeItem) {
					uni.showToast({
						title: '请选择客户类型',
						icon: 'none'
					})
					return
				}
				if (!selectArea || selectArea.length != 3) {
					uni.showToast({
						title: '请选择省市区',
						icon: 'none'
					})
					return
				}
				if (!customInfo.address) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					})
					return
				}
				let params = {
					address: customInfo.address,
					city: selectArea[1].value,
					county: selectArea[2].value,
					createUser: this.gUserInfo.userId,
					name: customInfo.name,
					province: selectArea[0].value,
					tel: customInfo.tel,
					type: typeItem.id,
				}
				if (this.pageType == 'edit') {
					params.id = this.customInfo.id
					this.$g_api.saleslipEditCustomer(params).then(({
						data
					}) => {
						uni.showToast({
							title: '编辑成功'
						})
						uni.$emit('update-customerList')
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					})
				} else {
					this.$g_api.saleslipSaveCustomer(params).then(({
						data
					}) => {
						uni.showToast({
							title: '添加成功'
						})
						uni.$emit('update-customerList')
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					})
				}
			},
			async onColumnChange({
				detail: {
					column,
					value
				}
			}) {
				let {
					tempAreaList
				} = this
				try {
					if (column == 0) {
						let cityList = await this.getDistrictList(tempAreaList[value].value)
						let districtList = await this.getDistrictList(cityList[0].id)
						districtList = districtList.map(item => {
							return {
								value: item.id,
								label: item.districtName
							}
						})
						cityList = cityList.map((item, index) => {
							let children = []
							if (index == 0) {
								children = districtList
							} else {
								children = [{
									value: 0,
									label: '加载中'
								}]
							}
							return {
								children,
								value: item.id,
								label: item.districtName
							}
						})
						tempAreaList = tempAreaList.map((item, index) => {
							if (index == value) {
								item.children = cityList
							}
							return {
								children: item.children,
								value: item.id,
								label: item.districtName
							}
						})
						this.$set(this.areaList, 1, cityList)
						this.$set(this.areaList, 2, districtList)
					} else if (column == 1) {
						let districtList = await this.getDistrictList(cityList[value].id)
						districtList = districtList.map(item => {
							return {
								value: item.id,
								label: item.districtName
							}
						})

					} else if (column == 2) {

					}

				} catch (e) {
					//TODO handle the exception
				}

			},
			confirm(e) {
				console.log(e);
				this.selectArea = e
			}
		}
	}
</script>

<style scoped lang="scss">
	/deep/ .u-column-item {
		// height: 90rpx !important;
		// line-height: 90rpx !important;
	}

	input {
		text-align: right;
	}

	.app_arrow {
		padding-right: 30rpx;
		color: #999;

		&::after {
			right: 10rpx;
		}
	}

	.btn {
		margin-top: 70rpx;
	}

	.customerTypePop {
		position: relative;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 30rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 30rpx);
	}

	.customerTypePop-close {
		position: absolute;
		right: 30rpx;
		top: 24rpx;
		width: 40rpx;
		height: 40rpx;
	}

	.customerTypePop-header {
		line-height: 90rpx;
		text-align: center;
	}

	.customerTypePop-main {
		padding: 30rpx 14rpx 30rpx 30rpx;
		box-sizing: border-box;
		min-height: 230rpx;
	}

	.customerTypePop-main_item {
		display: inline-block;
		min-width: 220rpx;
		margin-right: 14rpx;
		margin-bottom: 20rpx;
		padding: 16rpx 20rpx;
		text-align: center;
		border-radius: 10rpx;
		box-sizing: border-box;
		font-size: 26rpx;
		background-color: #f2f2f2;

		&.active {
			background-color: #fff;
			border: 1px solid $g-main-color;
			color: $g-main-color;
		}
	}

	.customerTypePop-btn {}

	.picker {
		width: 520rpx;
		line-height: 40rpx;
		padding: 12rpx 30rpx 12rpx 0;
		text-align: right;
	}
</style>
